import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateLikeDto } from './dto/create-like.dto';
import { Like } from './entities/like.entity';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { _BusinessTypeList } from '../utils';
import { Blog } from '../blog/entities/blog.entity';
import { Daily } from '../daily/entities/daily.entity';
import { Comment } from '../comment/entities/comment.entity';
@Injectable()
export class LikeService {
  @InjectEntityManager()
  private manage: EntityManager;

  // 点赞
  async create(createLikeDto: CreateLikeDto) {
    const { createId, userId, authorId, type, ip } = createLikeDto;
    const like = new Like();
    like.createId = createId;
    like.userId = userId;
    like.authorId = authorId;
    like.type = type;
    like.ip = ip || ''
    like[_BusinessTypeList[type] + 'Id'] = createId;
    try {
      const res = await this.manage.save(Like, like);
      if (res?.id) {
        let incrementResult = null
        if (type == 1) {
          incrementResult = await this.manage.increment(
            Blog,
            { id: createId },
            'thumbs_up_times',
            1,
          );
        } else if (type == 2) {
          incrementResult = await this.manage.increment(
            Daily,
            { id: createId },
            'like',
            1,
          );
        } else if (type == 3) {
          incrementResult = await this.manage.increment(
            Comment,
            { id: createId },
            'like',
            1,
          );
        }
        console.log('incrementResult:', incrementResult)
        if (incrementResult?.affected === 1) {
          return '点赞成功';
        } else {
          throw new HttpException('点赞失败', HttpStatus.BAD_REQUEST);
        }
      } else {
        throw new HttpException('点赞失败', HttpStatus.BAD_REQUEST);
      }
    } catch (error) {
      throw new HttpException(error, HttpStatus.BAD_REQUEST);
    }
  }

  // 取消点赞
  async remove(data: {
    id?: number;
    type: number;
    createId: number;
    userId?: number;
  }) {
    const { id, type, createId, userId } = data;
    if (id) {
      await this.manage.delete(Like, id);
    } else {
      await this.manage.delete(Like, {
        createId,
        type,
        userId,
      });
    }
    if (type == 1) {
      return await this.manage.decrement(
        Blog,
        { id: createId },
        'thumbs_up_times',
        1,
      );
    } else if (type == 2) {
      return await this.manage.decrement(Daily, { id: createId }, 'like', 1);
    } else if (type == 3) {
      return await this.manage.decrement(Comment, { id: createId }, 'like', 1);
    }
  }

  async removeByCreateId(createId: number) {
    await this.manage.delete(Like, {
      createId: createId,
    });
  }

  async unlikeSomething(data: {
    createId: number;
    type: number;
    userId: number;
  }) {
    await this.manage.delete(Like, {
      createId: data.createId,
      type: data.type,
      userId: data.userId,
    });
  }
  // 业务id + 业务类型查询
  async findByCreateIdAndType(data: {
    createId?: number;
    type: number;
    userId?: number;
  }) {
    const where: { createId?: number; type?: number; userId?: number } = {};
    if (data.type) {
      where.type = data.type;
    }
    if (data?.createId) {
      where.createId = data.createId;
    }
    if (data?.userId) {
      where.userId = data.userId;
    }
    try {
      const [likeList, total] = await this.manage.findAndCount(Like, {
        where: where,
      });
      return {
        data: likeList,
        total,
      };
    } catch (error) {
      throw new HttpException(error, HttpStatus.BAD_REQUEST);
    }
  }

  async findLikeByUserIdAndType(userId: number, type: number) {
    const res = await this.manage.find(Like, {
      where: {
        userId: userId,
        type: type,
      },
    });
    return res;
  }

  async queryLikeTotal(userId: number) {
    try {
      const [, total] = await this.manage.findAndCountBy(Like, {
        userId: userId,
      });
      return {
        total,
      };
    } catch (error) {
      throw new HttpException(error, HttpStatus.BAD_REQUEST);
    }
  }
}
